package com.xm.limiter;

/**
 * 一、计数器算法
 */
public class CounterLimiter01 implements Limiter {
    private final int limit; // 限流阈值
    private final long interval; // 时间窗口（毫秒）
    private long lastTime = System.currentTimeMillis();
    private int counter = 0;

    /**
     * 计数器算法：对流量突发容忍度较高的简单场景
     * @param limit 限流阈值
     * @param interval 时间窗口（毫秒）
     */
    public CounterLimiter01(int limit, long interval) {
        this.limit = limit;
        this.interval = interval;
    }

    @Override
    public synchronized boolean tryAcquire() {
        long now = System.currentTimeMillis();
        if (now - lastTime > interval) {
            lastTime = now;
            counter = 0;
        }
        if (counter < limit) {
            counter++;
            return true;
        }
        return false;
    }
}